from sqlalchemy import Result, select
from sqlalchemy.ext.asyncio import AsyncSession

from scaner.core.models import User, TgChatReference
from scaner.core.config.log_config import MyLogger

main_logger = MyLogger("main")
logger = main_logger.getChild("user")  # type: ignore


async def get_user_by_phone(
    phone: str,
    session: AsyncSession,
) -> User | None:
    logger.info("get_user_by_phone")  # type: ignore

    stmt = select(User).where(User.phone == phone)
    result: Result = await session.execute(stmt)
    user: User | None = result.scalar_one_or_none()
    return user


async def check_user_in_refer(user: User, session: AsyncSession) -> TgChatReference | None:
    logger.info("check_user_in_refer")

    stmt = select(TgChatReference).where(TgChatReference.user_id == user.id)
    result: Result = await session.execute(stmt)
    tg_chat_reference: TgChatReference | None = result.scalar_one_or_none()
    return tg_chat_reference


async def get_user_by_chat_id(chat_id: int, session: AsyncSession) -> User | None:
    stmt = select(TgChatReference).where(TgChatReference.chat_id == chat_id)

    result: Result = await session.execute(stmt)
    reference: TgChatReference | None = result.scalar_one_or_none()

    return reference.user if reference else None
